<?php
Doo::loadModelAt('FrbFlatChambreres', 'frbFlat');
class frbFlat_MainController extends DooController
{

  private $_name = 'frb Flat';
  private $_col = 1;

  public function __construct()
  {
    $this->view()->setTagClass("TemplateTag", "frbFlat");
  }


  /**
   *
   * Retourne le widget du module
   * @return Array [name]=>[contenu] contenu du widget
   */
  public function getWidget()
  {
    echo '<h1>Gestion des appartements</h1><p>Planning, reservations, etc.</p>';

  }

  /**
   *
   * Retourne les propriétés du widget Son nom et son nombre de colonne
   * @return Array [name]=>[nbColonne]
   */
  public function getWidgetProperties()
  {
    echo $this->_col;
  }

  public function getWidgetTitle()
  {
    echo "Appartements";
  }

  public function getMenu()
  {
    echo  "Appartements";
  }

  public function index()
  {
    $data['baseurl'] = Doo::conf()->APP_URL;
    Doo::loadControllerAt('FrbFlatClientController', 'frbFlat');
    $controller = new FrbFlatClientController();
    if ($this->isAjax()) {
      if ($this->isPost()) {
        if (!empty($_POST['change_dispo'])) {
          $controller->changeDispo();
          echo true;
          return ;
        }
      }
    }
    if ($controller->isFull()) {
      $data['dispo-name'] = "Rendre disponible";
      $data["dispo-css"] = "to-no-dispo";
      $data['dispo-text'] = "n'y a pas d'appartements";
    } else {
      $data['dispo-name'] = "Rendre indisponible";
      $data["dispo-css"] = "to-dispo";
      $data['dispo-text'] = "reste des appartements";
    }

    //Mouvements
    Doo::loadModelAt('FrbFlatChambre', 'frbFlat');
    Doo::loadModelAt('FrbFlatImmeuble', 'frbFlat');
    Doo::loadModelAt('FrbFlatChambreres', 'frbFlat');
    $immeubles = new FrbFlatImmeuble();
    $immeubles = $this->db()->find($immeubles);
    $tab_display = array();
    $annee = date('Y');
    if (!empty($_GET['year']) && is_numeric($_GET['year']) && strlen($_GET['year']) == 4 && ($annee-1) == $_GET['year'] ) {
      $annee = $_GET['year'];
      $data["year"] = $annee;
      $data['anteYear'] = $annee + 1;
      $data['text-year'] = "Pour voir l'occupation de l'année en cours : ";
    } else {
      $data["year"] = $annee;
      $data['anteYear'] = $annee -1;
      $data['text-year'] = "Pour voir l'occupation de l'année précédente : ";
    }
    $debut_annee = $annee."-01-01";
    $fin_annee = $annee.'-12-31';
    foreach ($immeubles as $immeuble) {
      $immeuble_nom = $immeuble->imm_nom;
      $apparts = new FrbFlatChambre();
      $apparts->imm_fid = $immeuble->imm_id;
      $apparts = $this->db()->find($apparts);
      $app = array();
      foreach ($apparts as $appart) {
        $res = new FrbFlatChambreres();
        $res->cha_id = $appart->cha_id;
        //$res = $this->db()->find($res, array('asc'=>'chr_datedeb', 'where'=>"chr_datedeb BETWEEN '$debut_annee' AND '$fin_annee'"));
        $res = $this->db()->find($res, array('asc'=>'chr_datedeb', 'where'=>"(cha_id = $appart->cha_id) AND (chr_datedeb < '$debut_annee' AND ( chr_datefin = '0000-00-00' OR (chr_datefin BETWEEN '$debut_annee' AND '$fin_annee')) ) OR (chr_datedeb BETWEEN '$debut_annee' AND '$fin_annee')"));

        foreach ($res as $resa) {
          if ($resa->chr_datefin > $annee."-12-31" || $resa->chr_datefin == "0000-00-00") {
            $resa->chr_datefin = $annee."-12-31";
          }
          if ($resa->chr_datedeb < $debut_annee) {
            $resa->chr_datedeb = $debut_annee;
          }
        }
        $count = sizeof($res);
        $app[] = array("name"=>$appart->cha_num, "count"=>$count, "res"=>$res);
      }
      $tab_display[$immeuble->imm_nom] = $app;
    }
    $data["table"] = $this->tableMvt($tab_display);

    $this->render("index", $data);
  }

  private function tableMvt($array)
  {
    $table = "";
    foreach ($array as $immeuble=>$value) {
      $table .="<tr><td colspan='2' class='immeuble-td'>$immeuble</td></tr>";
      foreach ($value as $appart) {
        $resaPlus = "";
        if ($appart['count'] == 0) {
          $rowspan = 1;
          $resa = "<td class='empty-td'>Aucune occupation cette année</td>";
        } else {
          //Affichage de plusieurs réservation
          $rowspan = $appart['count'];
          $resa = "<td> ".$appart['res'][0]->chr_loca." du <b>".$this->getFrenchDate($appart['res'][0]->chr_datedeb)."</b> au <b>".$this->getFrenchDate($appart['res'][0]->chr_datefin)."</b></td>";
          if ($appart['count'] > 1) {
            for($i=1; $i<$appart['count']; $i++ ) {
              $resaPlus .= "<tr><td> ".$appart['res'][$i]->chr_loca." du <b>".$this->getFrenchDate($appart['res'][$i]->chr_datedeb)."</b> au <b>".$this->getFrenchDate($appart['res'][$i]->chr_datefin)."</b></td></tr>";
            }
          }
        }
        $table .= "<tr><td rowspan='$rowspan'>".$appart['name']."</td> ".$resa."</tr>";
        $table .= $resaPlus;
      }
    }
    return $table;
  }

  public function planning()
  {
    Doo::loadControllerAt('Month', 'frbFlat');
    Doo::loadControllerAt('FrbFlatClientController', 'frbFlat');
    Doo::loadModelAt('FrbFlatChambre', 'frbFlat');
    Doo::loadModelAt('FrbFlatImmeuble', 'frbFlat');
    $apparts_model = new FrbFlatChambre();
    $apparts_model->imm_fid = 1;
    $apparts_model = $this->db()->find($apparts_model);
    $reserv = new FrbFlatClientController();
    $last = array();
    $data['baseurl'] = Doo::conf()->APP_URL;
    if ($this->isAjax()) {
      if ($this->isPost()) {
        if (!empty($_POST['month']) && !empty($_POST['year']) && !empty($_POST['immeuble'])) {
          if (is_numeric($_POST['month']) && is_numeric($_POST['year'])) {
            $month = new Month($_POST['month'], $_POST['year']);
            if (is_numeric($_POST['immeuble'])) {
              $apparts_model = new FrbFlatChambre();
              $apparts_model->imm_fid = $_POST['immeuble'];
              $apparts_model = $this->db()->find($apparts_model);
            }
            foreach ($apparts_model as $appart) {
              $apparts["appartement-$appart->cha_num"] = "app$appart->cha_id";
              $last[$appart->cha_id] = $reserv->getSpecReservations($appart->cha_id, $month->month_number, $month->year);
            }
            $data['reserv'] = $last;
            $data['planning'] = $month->display($apparts);
            $data['apparts'] = $apparts;
            $this->view()->render('ajaxPlanning', $data);
            return;
          }
        }
      }
      echo "Un problème est survenu lors de la récupération du planning";
      return;
    }
    $data['cur_month'] = date('n');
    $data['cur_year'] = date('Y');
    $month = new Month($data['cur_month']);
    foreach ($apparts_model as $appart) {
      $apparts["appartement-$appart->cha_num"] = "app$appart->cha_id";
      $last[$appart->cha_id] = $reserv->getSpecReservations($appart->cha_id, $month->month_number, $month->year);
    }
    $data['immeubles'] = new FrbFlatImmeuble();
    $data['immeubles'] = $this->db()->find($data['immeubles']);
    $data['reserv'] = $last;
    $data['planning'] = $month->display($apparts);
    $data['apparts'] = $apparts;

    $this->render('planning', $data);
  }

  public function appartements()
  {
    Doo::loadModelAt('FrbFlatChambre', 'frbFlat');
    Doo::loadModelAt('FrbFlatImmeuble', 'frbFlat');
    Doo::loadModelAt('FrbFlatVille', 'frbFlat');
    Doo::loadPlugin("formFlatAdmin", "frbFlat");
    Doo::loadModelAt('FrbFlatChambreres', 'frbFlat');
    $appart = new FrbFlatChambre();
    $immeubles = new FrbFlatImmeuble();
    $data['baseurl'] = Doo::conf()->APP_URL;
    /** AJAX **/
    if ($this->isAjax()) {
      if ($this->isPost()) {

        /** Récupération des images **/
        if (!empty($_POST['get_pictures']) && !empty($_POST['id_flat'])) {
          Doo::loadControllerAt('FrbFlatClientController', 'frbFlat');
          $pictures = new FrbFlatClientController();
          $data['pictures'] = $pictures->getPictures($_POST['id_flat']);
          if (empty($data['pictures'])) {
            echo "Aucune image pour cet appartement";
            return;
          }
          $this->view()->render('ajaxPictures', $data);
          return;
        }
        /** Suppression d'une image **/
        if (!empty($_POST['del_picture']) && !empty($_POST['id_pic']) && !empty($_POST['id_flat'])) {
          Doo::loadModelAt('FrbFlatPictures', 'frbFlat');
          $picture = new FrbFlatPictures();
          $picture->cha_pic = $_POST['id_pic'];
          $picture->cha_id = $_POST['id_flat'];
          $this->db()->delete($picture);
          //On supprime aussi l'image sur le serveur
          $path = Doo::conf()->SITE_PATH.'global/img/appartements/pictures/';
          unlink($path.$_POST['id_pic']);
          unlink($path.'thumbnails/'.$_POST['id_pic']);
          return;
        }

        /** Récupère réservation **/
        if (!empty($_POST['get_reservation']) && !empty($_POST['id'])) {
          $reservations = new FrbFlatChambreres();
          $reservations->cha_id = $_POST['id'];
          $data['reservations'] = $this->db()->find($reservations, array('asc'=>'chr_datedeb'));
          if (empty($data['reservations'])) {
            //Aucune réservation
            echo "Aucune réservation";
          } else {
            foreach ($data['reservations'] as $k) {
              $sock = explode('-', $k->chr_datedeb);
              $k->chr_datedeb = $sock[2].'/'.$sock[1].'/'.$sock[0];
              $sock = explode('-', $k->chr_datefin);
              $k->chr_datefin = $sock[2].'/'.$sock[1].'/'.$sock[0];
            }

            $this->view()->render('ajaxReservation', $data);
          }
          return;
        }
        /** Ajoute nouvelle réservation **/
        if ( !empty($_POST['reservation_indicator']) && !empty($_POST['id'])) {
          /** Check reservation valid) **/
$formCh = formReservationAdmin($data['baseurl']);
          /*var_dump($_POST);
          return;*/
          if (!$formCh->isValid($_POST)) {
            echo "Formulaire non valide";
            var_dump($_POST);
            return;
          }
          $reservation = new FrbFlatChambreres();
          $reservation->chr_loca =  stripslashes($_POST['locataire']);
          $reservation->cha_id = $_POST['id'];
          $reservation->chr_firstname = stripslashes($_POST['prenom']);
          $reservation->chr_daten = $_POST['daten'];
          $reservation->chr_lieun =  stripslashes($_POST['lieun']);
          $reservation->chr_entree = $_POST['date_entree'];
          $reservation->chr_addr =  stripslashes($_POST['adresse']);
          $reservation->chr_dept =  stripslashes($_POST['dept']);
          $reservation->chr_ville =  stripslashes($_POST['ville']);
          $tmp = explode('/', $_POST['datedeb']);
          $reservation->chr_datedeb = $tmp[2].'-'.$tmp[1].'-'.$tmp[0];

          if ($_POST['datefin'] != "") {
            $tmp = explode('/', $_POST['datefin']);
            $reservation->chr_datefin = $tmp[2].'-'.$tmp[1].'-'.$tmp[0];
          } else {
            $reservation->chr_datefin="";
          }

          Doo::loadControllerAt("FrbFlatClientController", 'frbFlat');
          $verif = new FrbFlatClientController();

          if ($_POST['reservation_indicator'] == "new") {
            if (!$verif->validReservation($reservation->chr_datedeb, $reservation->chr_datefin, $_POST['id'])) {
              echo "Attention certaines dates se chevauchent\n\tModifications non enregistrées";
              return;
            }
            $this->db()->insert($reservation);
            return;
          }
          if ($_POST['reservation_indicator'] == "change") {
            if (!$verif->validReservation($reservation->chr_datedeb, $reservation->chr_datefin, $_POST['id'], $_POST['chambreres'])) {
              echo "Attention certaines dates se chevauchent\n\tModifications non enregistrées";
              return;
            }
            $reservation->chr_id = $_POST['chambreres'];
            $this->db()->update($reservation);
            return;
          }


          return;
        }

        if (!empty($_POST['del_reservation']) && !empty($_POST['reservation_id']) && is_numeric($_POST['reservation_id'])) {
          $reservation = new FrbFlatChambreres();
          $reservation->chr_id = $_POST['reservation_id'];
          $this->db()->delete($reservation);
          echo "taaac";
          return ;
        }

        //add/change Flat
        if (!empty($_POST['action-indicator'])) {
          $appart = new FrbFlatChambre();
          $appart->cha_loy_low = $_POST['loyer'];
          $appart->cha_num = $_POST['name'];
          $appart->imm_fid = $_POST['immeuble'];
          $post_surface = $_POST['surface'];
          $appart->cha_surf = $post_surface;
          $appart->cha_det = stripslashes($_POST['detail']);
          if ($_POST['action-indicator'] == "new") {
            $this->db()->insert($appart);
            echo "ok";
          } else {
            $appart->cha_id = $_POST['id'];
            $this->db()->update($appart);
            echo "ok";
          }
          return;
        }

        //Gestion du filtre sur les immeubles
        if (!empty($_POST['immeuble'])) {
          if (is_numeric($_POST['immeuble'])) {
            $id = $_POST['immeuble'];
            $appart = $appart->relate('FrbFlatImmeuble', array('where'=>"imm_id = $id"));
          } else {
            $appart = $appart->relate('FrbFlatImmeuble',  array("asc" => "imm_id"));
          }
          if (empty($appart)) { echo "Aucun appartement"; return; }
          foreach ($appart as $k=>$value) {
            $value->FrbFlatImmeuble = $value->FrbFlatImmeuble->relate('FrbFlatVille');
            $value->FrbFlatImmeuble = $value->FrbFlatImmeuble[0];
          }
          $data['allApparts'] = $appart;
          $this->view()->render('ajaxAppartements', $data);
          return;
        }
      }

      echo "Erreur de requête";
      return;
    }

    $appart = $appart->relate('FrbFlatImmeuble', array("asc" => "imm_id"));
    if (!empty($appart)) {
      foreach ($appart as $k=>$value) {
        $value->FrbFlatImmeuble = $value->FrbFlatImmeuble->relate('FrbFlatVille');
        $value->FrbFlatImmeuble = $value->FrbFlatImmeuble[0];
      }
    }
    //$appart contient un tuple avec appart immeuble ville
    //{{allApparts' value.@FrbFlatImmeuble.@FrbFlatVille.@vil_nom}}
    $data['allApparts'] = $appart;
    $data['immeubles'] = $this->db()->find($immeubles);
    $form = formFlatAdmin("", $data['immeubles']);
    $form_reservation = formReservationAdmin("");
    $data['formFlatAdmin'] = $form->render();
    $data['formReservationAdmin'] = $form_reservation->render();

    $this->view()->render('appartements', $data);

  }

  public function taxe() 
  {
    $co =  (isset($_SESSION['connected']) && $_SESSION['connected'] == 1) ? true : false;
    if (!$co) return 404;
    $data['baseurl'] = Doo::conf()->APP_URL;
    Doo::loadModelAt('FrbFlatChambre', 'frbFlat');
    Doo::loadModelAt('FrbFlatImmeuble', 'frbFlat');
    Doo::loadModelAt('FrbFlatChambreres', 'frbFlat');
    $immeubles = new FrbFlatImmeuble();

    $immeubles = $this->db()->find($immeubles);
    $tab_taxe = array();
    $year = date('Y');
    $data['year-to'] = $year-1;
    if (!empty($_GET['year']) && is_numeric($_GET['year']) && strlen($_GET['year']) == 4 && ($year-1) == $_GET['year'] ) {
      $data['year-to'] = $year;
      $year = $_GET['year'];
    }
    $debut_annee = $year."-01-01";
    $fin_annee = $year.'-12-31';
    $titre = "RELEVE LOCATAIRES 1ER JANVIER ".$year;
    foreach ($immeubles as $immeuble) {
      $enterprise = "";
      if ($immeuble->imm_id==1) {
        $enterprise = "SEP LARIE FRERES";
      }
      if ($immeuble->imm_id==2) {
        $enterprise = "SARL LARIE FRERES";
      }
      $adresse = $immeuble->imm_adr." 13001 Marseille";
      $content="";

      $apparts = new FrbFlatChambre();
      $apparts->imm_fid = $immeuble->imm_id;
      $apparts = $this->db()->find($apparts);
      $rows = array();
      foreach ($apparts as $appart) {
        $res = new FrbFlatChambreres();
        $res->cha_id = $appart->cha_id;
        //$res = $this->db()->find($res, array('asc'=>'chr_datedeb', 'where'=>"chr_datedeb BETWEEN '$debut_annee' AND '$fin_annee'"));
        $res = $this->db()->find($res, array('asc'=>'chr_datedeb', 'where'=>"(
          cha_id = $appart->cha_id) 
        AND (
          chr_datedeb < '$debut_annee' 
          AND (  
            (chr_datefin  BETWEEN '$debut_annee' AND '$fin_annee')
            OR chr_datefin = '0000-00-00' )
        ) OR 
        (
          chr_datedeb = '$debut_annee'
          )"));
        //$res = $this->db()->find($res, array('asc'=>'chr_datedeb', 'where'=>"(cha_id = $appart->cha_id) AND (chr_datedeb < '$debut_annee' AND ((chr_datefin  BETWEEN '$debut_annee' AND '$fin_annee')) OR chr_datefin = '0000-00-00') OR (chr_datedeb BETWEEN '$debut_annee' AND '$fin_annee')"));
        foreach ($res as $resa) {
          if ($resa->chr_datefin == "0000-00-00") {
            $resa->chr_datefin = "";
          }
          if ($resa->chr_datefin > $year."-12-31") {
            $resa->chr_datefin = "";
          }
          $entreee = $this->getFrenchDate($resa->chr_datedeb);
          if ($resa->chr_datedeb < $debut_annee) {
            $resa->chr_datedeb = $debut_annee;
          }
          $rows[] = array(
            "nom"    =>  $resa->chr_loca, 
            "prenom"  =>  $resa->chr_firstname, 
            "daten"    =>  $resa->chr_daten,
            "lieun"    =>  $resa->chr_lieun,
            "lot"    =>  $appart->cha_num,
            "sm2"    =>  $appart->cha_surf,
            "entree"  =>  $entreee,
            "present"  =>  $this->getFrenchDate($resa->chr_datedeb),
            "depart"  =>  $this->getFrenchDate($resa->chr_datefin),
            "adresse"  =>  $resa->chr_addr,
            "ville"    =>  $resa->chr_ville,
            "dept"    =>  $resa->chr_dept
            );

        }
      }
      $content = $rows;
      $tab_taxe[] = array("title"=>$titre, "enterprise" => $enterprise, "address"=>$adresse, "content"=>$this->display_tab($content));

    }

    $data['tab_taxe'] = $tab_taxe;
    $this->render("taxe", $data);
  }

  private function display_tab($content) 
  {
    $table   ="<table class='taxe-table-html' border='1'>";
    $table  .="<tr> <th>nom</th> <th>prénom</th> <th class='shrink-text'>date de naissance</th> <th>lieu naissance</th> <th>lot</th> <th>s m2</th> <th>entrée</th> <th>présent</th> <th>Départ</th> <th>adresse</th> <th width='50px'>CP</th> <th>Ville</th> </tr>";
    $ant_lot="";
    foreach ($content as $row) {
      if ($ant_lot=="") {
        $table .= $this->display_row($row);
        $ant_lot = substr($row['lot'], 0, 1);
      } else {
        if (substr($row['lot'], 0, 1) != $ant_lot) {
          $table .= "<tr><td colspan='12'>-</td></tr>";
          $table .= $this->display_row($row);
          $ant_lot = substr($row['lot'], 0, 1);
        } else {
          $table .= $this->display_row($row);
          $ant_lot = substr($row['lot'], 0, 1);
        }
      }
    }


    $table  .="</table>";

    return $table;
  }

  private function display_row($row) 
  {
    $rtab = "";
    $rtab .= "<tr class='hover-line'>";
    $rtab .= "<td>".$row['nom']."</td> ";     $rtab .= "<td>".$row['prenom']."</td> ";   $rtab .= "<td>".$row['daten']."</td> ";   $rtab .= "<td>".$row['lieun']."</td> ";
    $rtab .= "<td>".$row['lot']."</td> ";      $rtab .= "<td>".$row['sm2']."</td> ";     $rtab .= "<td>".$row['entree']."</td> ";   $rtab .= "<td>".$row['present']."</td> ";
    $rtab .= "<td>".$row['depart']."</td> ";   $rtab .= "<td>".$row['adresse']."</td> ";   $rtab .= "<td>".$row['ville']."</td> ";   $rtab .= "<td>".$row['dept']."</td> ";
    $rtab .= "</tr>";

    return $rtab;
  }

  private function isPost() 
  {
    if ($_SERVER['REQUEST_METHOD'] == "POST") return true;
    else return false;
  }


  private function getFrenchDate($date, $format="0000-00-00") 
  {
    //return $date;
    if ($date == "") {
      return "";
    }
    $tmp = explode('-', $date);
    return $tmp[2].'/'.$tmp[1].'/'.$tmp[0];
  }

  public function histo() {
    $co =  (isset($_SESSION['connected']) && $_SESSION['connected'] == 1) ? true : false;
    if (!$co) return 404;
    $data['baseurl'] = Doo::conf()->APP_URL;
    $y = date('Y');
    for ($i=$y; $i>=2004 ; $i--) { 
      $data['year'][] = $i;
    }
    if (isset($_GET['year']) && is_numeric($_GET['year']) && $_GET['year'] >=2004 && $_GET['year'] <= $y) {
      $y = $_GET['year'];

    }
    $data['ye'] = $y;
    $data['table1'] = $this->getAllHistoTable(FrbFlatChambreres::_getAllMvtFromYear($y, 1));
    $data['table2'] = $this->getAllHistoTable(FrbFlatChambreres::_getAllMvtFromYear($y, 2));

    $this->render("histo", $data);
  }

  private function getAllHistoTable($data){
    $table   ="<table class='taxe-table-html' border='1'>";
    $table  .=" <tr> <th>lot</th> <th>nom</th> <th>prénom</th> <th class='shrink-text'>date de naissance</th> <th>lieu naissance</th> <th>entrée</th> <th>Départ</th> <th>adresse</th> <th width='50px'>CP</th> <th>Ville</th> </tr>";
    foreach ($data as $k) {
      //Traiter le cas zero
      $size = sizeof($k->FrbFlatChambreres);
      if ($size == 0) {
       $table .= "<tr class='hover-line'>";
       $table .= '<td>'.$k->cha_num.'</td>';
       for ($i=0; $i <=9 ; $i++) { 
         $table.='<td> NC </td>'; 
       }  
       $table .= "</tr>";          
     } 
     else {
       $table .= "<tr class='hover-line'>";
       $table .= "<td rowspan='".$size."'>".$k->cha_num.'</td>';
       $c = 0;
       foreach ($k->FrbFlatChambreres as $v) {
        $c++;
        if ($c >= 2) { $table .="<tr class='hover-line'>"; }
        $table .= '<td>'.$v->chr_loca.'</td>';
        $table .= '<td>'.$v->chr_firstname.'</td>';
        $table .= '<td>'.$v->chr_daten.'</td>';
        $table .= '<td>'.$v->chr_lieun.'</td>';
        $table .= '<td>'.$v->chr_datedeb.'</td>';
        $table .= '<td>'.$v->chr_datefin.'</td>';
        $table .= '<td>'.$v->chr_addr.'</td>';
        $table .= '<td>'.$v->chr_ville.'</td>';
        $table .= '<td>'.$v->chr_dept.'</td>';
        if ($c >= 2 ) { $table .="</tr>"; }
      }
      $table .= "</tr>";
    }
  }
  $table .= "</table>";
  return $table;
}

}